<template>
  <div class="user-management-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <el-button 
        type="primary" 
        icon="Plus" 
        @click="openAddUserDialog"
      >
        新增用户
      </el-button>
    </div>

    <!-- 用户表格 -->
    <el-table 
      :data="filteredUsers" 
      border 
      style="width: 100%; margin-top: 20px;"
      :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold' }"
    >
      <el-table-column 
        prop="id" 
        label="ID" 
        width="80" 
        align="center"
      ></el-table-column>
      <el-table-column 
        prop="name" 
        label="姓名" 
        align="center"
      ></el-table-column>
      <el-table-column 
        prop="email" 
        label="邮箱" 
        align="center"
      ></el-table-column>
      <el-table-column 
        prop="role" 
        label="角色" 
        align="center"
      >
        <template #default="scope">
          <el-tag :type="scope.row.role === 'admin' ? 'primary' : 'success'">
            {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column 
        prop="status" 
        label="状态" 
        align="center"
      >
        <template #default="scope">
          <el-switch 
            v-model="scope.row.status" 
            active-color="#13ce66" 
            inactive-color="#ff4949"
            :disabled="true"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column 
        label="操作" 
        width="200" 
        align="center"
      >
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            icon="Edit"
            @click="handleEdit(scope.row)"
          ></el-button>
          <el-button 
            type="danger" 
            size="small" 
            icon="Delete"
            @click="handleDelete(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="totalUsers"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑用户' : '新增用户'"
      :width="600"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userForm"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        style="margin-top: 20px;"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="formData.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="普通用户" value="user"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" active-text="启用" inactive-text="禁用"></el-switch>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="isEditMode ? handleUpdate() : handleCreate()"
        >
          {{ isEditMode ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';

// 模拟用户数据
const users = ref([
  { id: 1, name: '张三', email: 'zhangsan@example.com', role: 'admin', status: true, remark: '系统管理员' },
  { id: 2, name: '李四', email: 'lisi@example.com', role: 'user', status: true, remark: '普通用户' },
  { id: 3, name: '王五', email: 'wangwu@example.com', role: 'user', status: false, remark: '已停用' },
  { id: 4, name: '赵六', email: 'zhaoliu@example.com', role: 'user', status: true, remark: '' },
  { id: 5, name: '钱七', email: 'qianqi@example.com', role: 'user', status: true, remark: 'VIP用户' },
  { id: 6, name: '孙八', email: 'sunba@example.com', role: 'user', status: true, remark: '' },
  { id: 7, name: '周九', email: 'zhoujiu@example.com', role: 'user', status: false, remark: '长期未登录' },
  { id: 8, name: '吴十', email: 'wushi@example.com', role: 'user', status: true, remark: '' },
  { id: 9, name: '郑十一', email: 'zhengshiyi@example.com', role: 'user', status: true, remark: '' },
  { id: 10, name: '王十二', email: 'wangshier@example.com', role: 'user', status: true, remark: '' },
  { id: 11, name: '李十三', email: 'lishisan@example.com', role: 'user', status: true, remark: '' },
  { id: 12, name: '张十四', email: 'zhangshisi@example.com', role: 'user', status: false, remark: '' },
]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalUsers = computed(() => users.value.length);

// 过滤后的用户列表（用于分页）
const filteredUsers = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return users.value.slice(startIndex, startIndex + pageSize.value);
});

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置为第一页
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 对话框相关
const dialogVisible = ref(false);
const isEditMode = ref(false);
const currentEditId = ref(null);

// 表单数据
const formData = reactive({
  name: '',
  email: '',
  role: 'user',
  status: true,
  remark: ''
});

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
});

// 打开新增用户对话框
const openAddUserDialog = () => {
  // 重置表单
  formData.name = '';
  formData.email = '';
  formData.role = 'user';
  formData.status = true;
  formData.remark = '';
  
  isEditMode.value = false;
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row) => {
  // 填充表单数据
  formData.name = row.name;
  formData.email = row.email;
  formData.role = row.role;
  formData.status = row.status;
  formData.remark = row.remark || '';
  
  currentEditId.value = row.id;
  isEditMode.value = true;
  dialogVisible.value = true;
};

// 处理删除
const handleDelete = (row) => {
  ElMessage.confirm(
    `确定要删除用户 ${row.name} 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    users.value = users.value.filter(user => user.id !== row.id);
    ElMessage.success('删除成功');
  }).catch(() => {
    // 取消删除
  });
};

// 处理创建新用户
const handleCreate = () => {
  // 模拟表单验证通过
  const newId = Math.max(...users.value.map(u => u.id), 0) + 1;
  users.value.push({
    id: newId,
    name: formData.name,
    email: formData.email,
    role: formData.role,
    status: formData.status,
    remark: formData.remark
  });
  
  dialogVisible.value = false;
  ElMessage.success('用户创建成功');
};

// 处理更新用户
const handleUpdate = () => {
  const index = users.value.findIndex(u => u.id === currentEditId.value);
  if (index !== -1) {
    users.value[index] = {
      ...users.value[index],
      name: formData.name,
      email: formData.email,
      role: formData.role,
      status: formData.status,
      remark: formData.remark
    };
    
    dialogVisible.value = false;
    ElMessage.success('用户更新成功');
  }
};
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

h1 {
  margin: 0;
  font-size: 20px;
  color: #333;
}
</style>
